package com.sz.app.oss.api.common.contract;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.contract.entity.ContContract;
import com.sz.biz.common.contract.service.ContractStatusEnum;
import com.sz.biz.common.contract.service.ContractTypeEnum;
import com.sz.biz.common.contract.service.ServiceTypeEnum;
import com.sz.biz.common.contract.service.ContContractService;
import com.sz.biz.common.contract.dto.ContContractDto;
import com.sz.biz.common.contract.dto.ContContractFileDto;
import com.sz.biz.common.contract.dto.ContContractReturnDto;
import com.sz.biz.logistics.constants.ErrorCodes;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.DateUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Function: 合同-合同controller
 * Author: yanhong.xiao.<br>
 * Date: 2017-07-21 08:55:00.
 */
@RestController
@RequestMapping("${api}/contracts/contract-contracts")
@Api(description = " ", tags = "105-003，合同-合同管理")
public class ContContractController extends BaseController {
    @Autowired
    private ContContractService contractService;

    /**
     * 新增合同----基于模板创建
     */
    @ApiOperation(value = "新增合同-基于模板创建", notes = "新增合同<br>权限："+Permissions.BIZ_MGT_BASE_CONT_CONTRACT)
    @RequestMapping(value = "/templates", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_CONTRACT})
    public ResultDto saveByTemplate(@RequestBody @ApiParam(value = "要保存的数据", required = true) @Validated ContContractDto dto) {
        dto.setType(ContractTypeEnum.getIntegerCode(ContractTypeEnum.CONT_TEMPLATE));
        ContContractReturnDto returnDto = contractService.saveContract(dto);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_CONT);
        result.setData(returnDto);
        return result;
    }


    @ApiOperation(value = "新增合同-自定义上传文件", notes = "新增合同<br>权限："+Permissions.BIZ_MGT_BASE_CONT_CONTRACT)
    @RequestMapping(value = "/definitions", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_CONTRACT})
    public ResultDto saveByFile(@RequestBody @ApiParam(value = "要保存的数据", required = true) @Validated ContContractFileDto dto) {
        dto.setType(ContractTypeEnum.getIntegerCode(ContractTypeEnum.CONT_DEFINITION));
        ContContract contract = contractService.saveContractFile(dto);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_CONT);
        ContContractReturnDto returnDto = new ContContractReturnDto();
        returnDto.setId(contract.getId());
        result.setData(returnDto);
        return result;
    }


    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ApiOperation(value = "获取合同的详情", notes = "获取合同详情<br>权限:"+Permissions.BIZ_MGT_BASE_CONT_CONTRACT)
    public ResultDto getById(@PathVariable Integer id) {
        ContContractDto dto = contractService.getDtoById(id);
        ResultDto resultDto = new ResultDto();
        resultDto.setData(dto);
        return resultDto;
    }


    /**
     * 修改合同
     */
    @RequestMapping(value = "/templates/{id}", method = {RequestMethod.POST})
    @ApiOperation(value = "修改合同--基于模板", notes = "修改合同<br>")
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_CONTRACT})
    public ResultDto updateContract(@RequestBody ContContractDto dto, @PathVariable Integer id) {
        dto.setId(id);
        ContContractReturnDto returnDto = contractService.updateContract(dto);
        ResultDto result ;
        if (StringUtils.isNotBlank(returnDto.getFileUrl())){
            //生成合同,返回生成合同成功
            result = getOperateSuccessDto(MessagesCodes.MODULE_CONT_CONTRACT_GENERATE_SUCCESS);
        }else{
            result = getUpdateSuccessDto(MessagesCodes.MODULE_CONT);
        }
        result.setData(returnDto);
        return result;
    }


    /**
     * 修改合同----此接口暂时不用
     */
    @RequestMapping(value = "/definitions/{id}", method = {RequestMethod.POST})
    @ApiOperation(value = "修改合同--基于文件", notes = "修改合同<br>")
    public ResultDto updateContractFile(@RequestBody ContContractFileDto dto, @PathVariable Integer id) {
        dto.setId(id);
        contractService.updateContractFile(dto);
        ResultDto result = getUpdateSuccessDto(MessagesCodes.MODULE_CONT);
        return result;
    }


    /**
     * @param
     * @param pageIndex
     * @param pageSize
     * @param sort
     * @param asc
     * @param startTime
     * @param endTime
     * @param serviceType
     * @param createUserName
     * @return
     */
    @ApiOperation(value = "合同列表以及查询接口", notes = "根据指定条件获取数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true"),
            @ApiImplicitParam(name = "serviceType", value = "业务类型", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "templateName", value = "模板名称,模糊查询", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "title", value = "合同标题", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "合同状态", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "createUserName", value = "创建者名称,模糊查询", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResultDto find(@RequestParam(required = false, defaultValue = "1") int pageIndex,
                          @RequestParam(required = false, defaultValue = "10") int pageSize,
                          @RequestParam(required = false) String sort,
                          @RequestParam(required = false, defaultValue = "true") Boolean asc,
                          @RequestParam(required = false, defaultValue = "") String startTime,
                          @RequestParam(required = false, defaultValue = "") String endTime,
                          @RequestParam(required = false, defaultValue = "0") Integer serviceType,
                          @RequestParam(required = false) String templateName,
                          @RequestParam(required = false) String title,
                          @RequestParam(required = false, defaultValue = "0") Integer status,
                          @RequestParam(required = false) String createUserName
    ) {
        QueryParams qp = new QueryParams(pageSize, pageIndex, null, sort, asc);
        if (null != ServiceTypeEnum.valueOfEnum(String.valueOf(serviceType))) {
            qp.put("serviceType", serviceType);
        }
        if (StringUtils.isNotBlank(title)) {
            title  = com.sz.common.base.utils.StringUtils.replaceSqlPattern(title);
            qp.put("title", title.trim());
        }
        // 先查找createUserName的ids
        if (StringUtils.isNotBlank(createUserName)) {
            createUserName  = com.sz.common.base.utils.StringUtils.replaceSqlPattern(createUserName);
            qp.put("createUserName", createUserName.trim());
        }
        if (null != ContractStatusEnum.valueOfEnum(String.valueOf(status))) {
            qp.put("status", status);
        }
        if (StringUtils.isNotBlank(templateName)) {
            templateName  = com.sz.common.base.utils.StringUtils.replaceSqlPattern(templateName);
            qp.put("templateName", templateName);
        }
        try {
            if (!ObjectUtils.isEmpty(startTime)) {
                qp.put("startTime", DateUtils.convertToDate(startTime, DateUtils.FORMAT_DETAIL));
            }
            if (!ObjectUtils.isEmpty(endTime)) {
                qp.put("endTime", DateUtils.convertToDate(endTime, DateUtils.FORMAT_DETAIL));
            }
        } catch (ParseException e) {
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "时间参数传入有误");
        }
        return contractService.findSimpleDtoPages(qp);
    }


    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除</br>:权限:"+Permissions.BIZ_MGT_BASE_CONT_CONTRACT, httpMethod = "POST")
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CONT_CONTRACT})
    public ResultDto batchDelete(@RequestBody @ApiParam(value = "要删除的id集合", required = true) List<Integer> ids) {
        contractService.batchDeleteByIds(ids);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_CONT);
        return dto;
    }


}
